package com.solcoo.service;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;

import org.springframework.stereotype.Service;

import com.solcoo.dao.MerchantTypeDao;
import com.solcoo.dao.PriceTicketDao;
import com.solcoo.dao.RechargeDao;
import com.solcoo.dao.YongHuDao;
import com.solcoo.dao.ZhangHuDao;
import com.solcoo.dao.ZheKouDao;
import com.solcoo.json.MerchantInfoJson;
import com.solcoo.json.MerchantSimpleInfoJson;
import com.solcoo.pojo.DingDan;
import com.solcoo.pojo.MerchantType;
import com.solcoo.pojo.PriceTicket;
import com.solcoo.pojo.RechargeInfo;
import com.solcoo.pojo.YongHu;
import com.solcoo.pojo.ZhangHu;
import com.solcoo.pojo.ZheKou;
import com.solcoo.util.MapUtil;
import com.solcoo.util.SendMsgUtil;

@Service
public class YongHuService {

	@Resource
    private YongHuDao yongHuDao;
	@Resource
    private ZhangHuDao zhangHuDao;
	@Resource
    private DingDanService dingDanService;
	@Resource
    private PriceTicketDao priceTicketDao;
    @Resource
    private MerchantTypeDao merchantTypeDao;
    @Resource
    private RechargeDao rechargeDao;
    @Resource
    private ZheKouDao zheKouDao;
    
    public boolean newMembership(Integer id, Integer merchantId) throws Exception{
    	// 校验商户ID是否存在
        String merchantIdS = merchantId + "";
        while(merchantIdS.length() < 5) {
        	merchantIdS = "0" + merchantIdS;
        }
        YongHu merchant = yongHuDao.selectUserByYonghum(merchantIdS);
        if(merchant==null || !"1".equals(merchant.getEnabled())) {
    		return false;
        }

    	// 校验个人ID是否存在
        String customerIdS = id + "";
        while(customerIdS.length() < 5) {
        	customerIdS = "0" + customerIdS;
        }
        YongHu customer = yongHuDao.selectUserByYonghum(customerIdS);
        if(customer == null) {
    		return false;
        }
        
        ZhangHu zh = zhangHuDao.query(merchantId, id);
        if(zh == null) {
        	// 增加商户中的关注人数
            boolean operation = yongHuDao.addMemberCount(merchantId);
            if(!operation) {
            	return false;
            }
            
            zh = new ZhangHu();
            zh.setShanghuid(merchantId);
            zh.setGerenid(id);
            zh.setDengji(0);
            zh.setJingyanz(0);
            zh.setShifougz("1");
            zh.setYue(0);
            zh.setZhekoul(0);
            zh.setZongxf(0);
            addPriceTicketDao(zh,id);
        } else if(!"1".equals(zh.getShifougz())) {
            boolean operation = yongHuDao.addMemberCount(merchantId);
            if(!operation) {
            	return false;
            }
            zh.setShifougz("1");
            zhangHuDao.update(zh);
        }
        return true;
    }

    /**
     * 获取抵价券信息，并且增加一条订单，充值到用户账号上，发送短信提醒
     * @param zh
     * @param userId
     */
    private void addPriceTicketDao(ZhangHu zh,int userId) throws Exception {
        PriceTicket pt = priceTicketDao.selectPriceTicket(zh.getShanghuid());
        if(pt == null) {
            zhangHuDao.add(zh);
            return ;
        }
        String yonghum = userId+"";
        while(yonghum.length() < 5) {
            yonghum = "0" + yonghum;
        }
        String merchantId = zh.getShanghuid()+"";
        while(merchantId.length() < 5) {
            merchantId = "0" + merchantId;
        }
        YongHu yh = yongHuDao.selectUserByYonghum(yonghum);
        YongHu merchant = yongHuDao.selectUserByYonghum(merchantId);
        double freeAmount = pt.getFreeAmount();

        if(freeAmount > 0) {
	        DingDan dd = new DingDan();
	        dd.setFreeAmount(freeAmount);
	        dd.setGerenid(userId);
	        dd.setJine(0);
	        dd.setLeixing("1");
	        dd.setShanghuid(Integer.valueOf(merchantId));
	        dingDanService.throwExcepshRecharge(dd, yh.getShoujih(), "0");

	        // 给客户发的信息
	        String m = yh.getShoujih();
	        String c = "您已在“"+merchant.getDianming()+
	                "”充值"+freeAmount+"元，账户余额"+BigDecimal.valueOf(zh.getYue()).add(BigDecimal.valueOf(freeAmount)).doubleValue()+"元，" +
	                "等级"+zh.getDengji()+"级 ";
	        
	        m += "," + merchant.getShoujih();
	        c += "{|}" + "（" + yh.getYonghum() + "）已成功关注您 ，赠送"+freeAmount+"元抵价金 ";
	        SendMsgUtil sms = new SendMsgUtil(m, c);
	        new Thread(sms).start();
        } else {
        	zhangHuDao.add(zh);
        }
    }

    public Map<String, Object> getMerchantSimpleInfo(Integer id, String sortType, 
    		Double longitude, Double latitude, String merchantType) throws Exception{
        if(id == null || id == 0) {
            return null;
        }
        List<MerchantSimpleInfoJson> mis = yongHuDao.getMerchantSimpleInfos(merchantType);

        if(mis != null) {
            for(MerchantSimpleInfoJson mi : mis) {
            	// 维护优惠金额字段
                PriceTicket pt = priceTicketDao.selectPriceTicket(Integer.valueOf(mi.getMerchantId()));
                if(pt != null) {
                    mi.setFreeAmount(pt.getFreeAmount());
                } else {
                    mi.setFreeAmount(0);
                }

                // 维护是否关注、是否显示优惠券/抵字段
                mi.setHasDi(false);
                ZhangHu zh = zhangHuDao.query(Integer.parseInt(mi.getMerchantId()), id);
                if(zh != null) {
                	if("1".equals(zh.getShifougz())) {
                		mi.setAttention(true);
                	} else {
                		mi.setAttention(false);
                	}
                	mi.setTicketFlag("0");
                } else {
                	mi.setTicketFlag("1");
                	// 维护“抵”是否显示
                	if(mi.getFreeAmount()>0)
                		mi.setHasDi(true);
                }
                
                // 计算维护距离
                if(latitude!=null && longitude!=null && mi.getLatitude()!=null && mi.getLongitude()!=null
                		&& latitude!=0 && longitude!=0 && mi.getLatitude()!=0 && mi.getLongitude()!=0) {
                	mi.setDistance((long)MapUtil.getDistance(latitude, longitude, mi.getLatitude(), mi.getLongitude()));
                } else {
                	mi.setDistance(-1l);
                }
                
                // 维护“惠卡”状态
                List<RechargeInfo> ris = rechargeDao.selectRechargeInfo(mi.getMerchantId());
                if(ris!=null && ris.size()>0) {
                	mi.setHasHui(true);
                } else {
                	mi.setHasHui(false);
                }
                List<ZheKou> zks = zheKouDao.queryListByShid(Integer.parseInt(mi.getMerchantId()));
                if(zks!=null && zks.size()>0) {
                	mi.setHasKa(true);
                } else {
                	mi.setHasKa(false);
                }
            }
        }
        if(sortType==null || !"2".equals(sortType)) {
        	Collections.sort(mis);
        }
        
        // 获取客户分类
        List<MerchantType> merchantTypeList = merchantTypeDao.getList();
        
        Map<String, Object> map = new HashMap<String, Object>();
		map.put("myList", mis);
		map.put("result", true);
		map.put("merchantTypeList", merchantTypeList);
        return map;
    }

    public boolean cacelRelation(Integer id, Integer merchantId)
            throws Exception {
    	ZhangHu zh = zhangHuDao.query(merchantId, id);
        // 账户是已关注才执行取消操作
        if(zh != null && "1".equals(zh.getShifougz())) {
            boolean operation = yongHuDao.decreaseMemberCount(merchantId);
            if(operation) {
                zh.setShifougz("0");
                zhangHuDao.update(zh);
                return true;
            }
        }
        return false;
    }

    public List<MerchantInfoJson> getMerchantList(String merchantType) throws Exception {
    	List<MerchantInfoJson>  mijs = yongHuDao.getMerchantList(merchantType);
    	
    	List<MerchantInfoJson> nmijs = new ArrayList<MerchantInfoJson>();
    	
    	MerchantInfoJson merchantInfoJson = null;
    	for (int i = 0; i < mijs.size(); i++) {
    		merchantInfoJson = mijs.get(i);
    		
    		merchantInfoJson.setActivityList(rechargeDao.selectRechargeInfo(merchantInfoJson.getYonghum()));
    		
    		nmijs.add(merchantInfoJson);
    	}
    	
    	return nmijs;
    }
    
	public Map<String, Object> valiPhone(String phone) {
		boolean result = false;
		
		try {
			result = yongHuDao.getUserByPhone(phone);
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		Map<String, Object> map = new HashMap<String, Object>();
		
		if ( !result ) {
			map.put("result", false);
			map.put("msg", "手机号不存在");
			
			return map;
		}
		
		map.put("result", true);
		map.put("msg", "手机号正确");
		
		return map;
	}
	
	public Map<String, Object> valiPassword(String phone, String password) {
		boolean result = false;
		
		try {
			result = yongHuDao.getUserByPhoneAndPassword(phone, password);
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		Map<String, Object> map = new HashMap<String, Object>();
		
		if ( !result ) {
			map.put("result", false);
			map.put("msg", "密码不存在");
			
			return map;
		}
		
		map.put("result", true);
		map.put("msg", "密码正确");
		
		return map;
	}

	public Map<String, Object> webLogin(String phone, String password, String valicode, HttpSession session) {
		Map<String, Object> map = new HashMap<String, Object>();
		
		if (valicode == null || "".equals(valicode.trim())) {
			map.put("result", false);
			map.put("msg", "验证码不能为空");
			
			return map;
		}
		
		int code = (Integer) session.getAttribute("valicode");
		
		if (code != Integer.parseInt(valicode)) {
			map.put("result", false);
			map.put("msg", "验证码有误, 请重新输入");
			
			return map;
		}
		
		YongHu user = null;
		
		try {
			user = yongHuDao.getUser(phone, password);
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		session.setAttribute("user", user);
		if ("13735520642".equals(phone)) {
			session.setAttribute("admin", user);
		}
		
		if (user == null) {
			map.put("result", false);
			map.put("msg", "登录账号或登录密码有误");
			
			return map;
		}
		
		map.put("shanghuid", user.getYonghum());
		map.put("shoujih", phone);
		map.put("result", true);
		map.put("msg", "登录成功");
		
		return map;
	}

	public Integer getMemberCount(int shanghuid) {
		int memberCount = 0;
		
		try {
			memberCount = yongHuDao.getMemberCountByShanhuid(shanghuid);
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		return memberCount;
	}

	public Map<String, Object> updatePasswd(String telephone, String oldPasswd,
			String newPasswd) throws Exception {
		Map<String, Object> map = new HashMap<String, Object>();
		YongHu yh = yongHuDao.selectUserByPhone(telephone);
		if(!yh.getMima().equals(oldPasswd)) {
			map.put("result", false);
			map.put("failMsg", "旧密码输入错误");
			
			return map;
		}
		
		yongHuDao.updatePasswd(telephone, newPasswd);
		
		map.put("result", true);
		map.put("msg", "修改成功");
		return map;
	}
}
